const express = require('express')
const router = express.Router()
const auth = require('../../middleware/auth')
const logger = require('../../utils/logger')
const AntiCheatService = require('../../services/antiCheatService')
const RiskAssessmentService = require('../../services/riskAssessmentService')
const { AdView, User } = require('../../models')
const { Op } = require('sequelize')

/**
 * 检查管理员权限
 */
const checkAdminPermission = (req, res, next) => {
  if (req.user.role !== 'admin') {
    return res.status(403).json({
      success: false,
      code: 403,
      message: '权限不足'
    })
  }
  next()
}

/**
 * 获取风险统计数据
 */
router.get('/risk-stats', auth, checkAdminPermission, async (req, res) => {
  try {
    const { startDate, endDate } = req.query
    
    // 构建时间范围
    const timeRange = {}
    if (startDate && endDate) {
      timeRange.created_at = {
        [Op.between]: [new Date(startDate), new Date(endDate)]
      }
    } else {
      // 默认最近7天
      const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
      timeRange.created_at = {
        [Op.gte]: sevenDaysAgo
      }
    }
    
    // 获取统计数据
    const totalViews = await AdView.count({ where: timeRange })
    const completedViews = await AdView.count({
      where: { ...timeRange, is_completed: 1 }
    })
    
    // 获取可疑IP统计
    const suspiciousIPs = await AdView.findAll({
      attributes: [
        'ip_address',
        [sequelize.fn('COUNT', sequelize.col('id')), 'view_count'],
        [sequelize.fn('COUNT', sequelize.literal('CASE WHEN is_completed = 1 THEN 1 END')), 'completed_count']
      ],
      where: timeRange,
      group: ['ip_address'],
      having: sequelize.literal('COUNT(id) > 50'), // 观看次数超过50的IP
      order: [[sequelize.fn('COUNT', sequelize.col('id')), 'DESC']],
      limit: 20,
      raw: true
    })
    
    // 获取可疑用户统计
    const suspiciousUsers = await AdView.findAll({
      attributes: [
        'user_id',
        [sequelize.fn('COUNT', sequelize.col('id')), 'view_count'],
        [sequelize.fn('COUNT', sequelize.literal('CASE WHEN is_completed = 1 THEN 1 END')), 'completed_count']
      ],
      where: timeRange,
      group: ['user_id'],
      having: sequelize.literal('COUNT(id) > 40'), // 观看次数超过40的用户
      order: [[sequelize.fn('COUNT', sequelize.col('id')), 'DESC']],
      limit: 20,
      raw: true
    })
    
    res.json({
      success: true,
      code: 200,
      data: {
        overview: {
          totalViews,
          completedViews,
          completionRate: totalViews > 0 ? (completedViews / totalViews * 100).toFixed(2) : 0
        },
        suspiciousIPs: suspiciousIPs.map(ip => ({
          ipAddress: ip.ip_address,
          viewCount: parseInt(ip.view_count),
          completedCount: parseInt(ip.completed_count),
          completionRate: ip.view_count > 0 ? (ip.completed_count / ip.view_count * 100).toFixed(2) : 0
        })),
        suspiciousUsers: suspiciousUsers.map(user => ({
          userId: user.user_id,
          viewCount: parseInt(user.view_count),
          completedCount: parseInt(user.completed_count),
          completionRate: user.view_count > 0 ? (user.completed_count / user.view_count * 100).toFixed(2) : 0
        }))
      },
      message: '获取风险统计成功'
    })
  } catch (error) {
    logger.error('获取风险统计失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取风险统计失败'
    })
  }
})

/**
 * 评估用户风险
 */
router.post('/assess-user-risk', auth, checkAdminPermission, async (req, res) => {
  try {
    const { userId, ipAddress, userAgent } = req.body
    
    if (!userId) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '用户ID不能为空'
      })
    }
    
    const riskAssessment = await RiskAssessmentService.assessUserRisk(
      userId,
      ipAddress || '127.0.0.1',
      userAgent || 'Unknown'
    )
    
    // 记录风险评估结果
    await RiskAssessmentService.recordRiskAssessment(userId, ipAddress, riskAssessment)
    
    res.json({
      success: true,
      code: 200,
      data: riskAssessment,
      message: '风险评估完成'
    })
  } catch (error) {
    logger.error('评估用户风险失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '评估用户风险失败'
    })
  }
})

/**
 * 添加用户到黑名单
 */
router.post('/blacklist/user', auth, checkAdminPermission, async (req, res) => {
  try {
    const { userId, duration = 86400, reason = '管理员操作' } = req.body
    
    if (!userId) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '用户ID不能为空'
      })
    }
    
    await AntiCheatService.addUserToBlacklist(userId, duration, reason)
    
    logger.info(`管理员 ${req.user.id} 将用户 ${userId} 添加到黑名单`, {
      duration,
      reason
    })
    
    res.json({
      success: true,
      code: 200,
      message: '用户已添加到黑名单'
    })
  } catch (error) {
    logger.error('添加用户到黑名单失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '添加用户到黑名单失败'
    })
  }
})

/**
 * 添加IP到黑名单
 */
router.post('/blacklist/ip', auth, checkAdminPermission, async (req, res) => {
  try {
    const { ipAddress, duration = 86400, reason = '管理员操作' } = req.body
    
    if (!ipAddress) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: 'IP地址不能为空'
      })
    }
    
    await AntiCheatService.addIPToBlacklist(ipAddress, duration, reason)
    
    logger.info(`管理员 ${req.user.id} 将IP ${ipAddress} 添加到黑名单`, {
      duration,
      reason
    })
    
    res.json({
      success: true,
      code: 200,
      message: 'IP已添加到黑名单'
    })
  } catch (error) {
    logger.error('添加IP到黑名单失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '添加IP到黑名单失败'
    })
  }
})

/**
 * 检查用户是否在黑名单中
 */
router.get('/blacklist/user/:userId', auth, checkAdminPermission, async (req, res) => {
  try {
    const { userId } = req.params
    
    const isBlacklisted = await AntiCheatService.isUserBlacklisted(userId)
    
    res.json({
      success: true,
      code: 200,
      data: {
        userId,
        isBlacklisted
      },
      message: '检查完成'
    })
  } catch (error) {
    logger.error('检查用户黑名单状态失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '检查用户黑名单状态失败'
    })
  }
})

/**
 * 检查IP是否在黑名单中
 */
router.get('/blacklist/ip/:ipAddress', auth, checkAdminPermission, async (req, res) => {
  try {
    const { ipAddress } = req.params
    
    const isBlacklisted = await AntiCheatService.isIPBlacklisted(ipAddress)
    
    res.json({
      success: true,
      code: 200,
      data: {
        ipAddress,
        isBlacklisted
      },
      message: '检查完成'
    })
  } catch (error) {
    logger.error('检查IP黑名单状态失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '检查IP黑名单状态失败'
    })
  }
})

/**
 * 获取用户详细信息和风险分析
 */
router.get('/user-analysis/:userId', auth, checkAdminPermission, async (req, res) => {
  try {
    const { userId } = req.params
    
    // 获取用户基本信息
    const user = await User.findByPk(userId)
    if (!user) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '用户不存在'
      })
    }
    
    // 获取用户观看记录统计
    const totalViews = await AdView.count({
      where: { user_id: userId }
    })
    
    const completedViews = await AdView.count({
      where: {
        user_id: userId,
        is_completed: 1
      }
    })
    
    // 获取最近7天的观看记录
    const recentViews = await AdView.findAll({
      where: {
        user_id: userId,
        created_at: {
          [Op.gte]: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
        }
      },
      order: [['created_at', 'DESC']],
      limit: 50
    })
    
    // 分析IP使用情况
    const ipStats = await AdView.findAll({
      attributes: [
        'ip_address',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      where: { user_id: userId },
      group: ['ip_address'],
      order: [[sequelize.fn('COUNT', sequelize.col('id')), 'DESC']],
      limit: 10,
      raw: true
    })
    
    // 检查黑名单状态
    const isBlacklisted = await AntiCheatService.isUserBlacklisted(userId)
    
    res.json({
      success: true,
      code: 200,
      data: {
        user: {
          id: user.id,
          phone: user.phone,
          nickname: user.nickname,
          points: user.points,
          memberLevel: user.member_level,
          createdAt: user.created_at
        },
        statistics: {
          totalViews,
          completedViews,
          completionRate: totalViews > 0 ? (completedViews / totalViews * 100).toFixed(2) : 0,
          recentViewsCount: recentViews.length
        },
        recentViews: recentViews.map(view => ({
          id: view.id,
          adType: view.ad_type,
          platform: view.platform,
          isCompleted: view.is_completed,
          pointsRewarded: view.points_rewarded,
          ipAddress: view.ip_address,
          createdAt: view.created_at
        })),
        ipStats: ipStats.map(stat => ({
          ipAddress: stat.ip_address,
          count: parseInt(stat.count)
        })),
        isBlacklisted
      },
      message: '获取用户分析数据成功'
    })
  } catch (error) {
    logger.error('获取用户分析数据失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取用户分析数据失败'
    })
  }
})

/**
 * 批量处理可疑用户
 */
router.post('/batch-process-suspicious', auth, checkAdminPermission, async (req, res) => {
  try {
    const { action, userIds, reason = '批量处理可疑用户' } = req.body
    
    if (!action || !userIds || !Array.isArray(userIds)) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数错误'
      })
    }
    
    const results = []
    
    for (const userId of userIds) {
      try {
        switch (action) {
          case 'blacklist':
            await AntiCheatService.addUserToBlacklist(userId, 86400, reason)
            results.push({ userId, success: true, action: 'blacklisted' })
            break
          case 'monitor':
            await AntiCheatService.increaseMonitoring(userId, null)
            results.push({ userId, success: true, action: 'monitored' })
            break
          default:
            results.push({ userId, success: false, error: '未知操作' })
        }
      } catch (error) {
        results.push({ userId, success: false, error: error.message })
      }
    }
    
    logger.info(`管理员 ${req.user.id} 批量处理可疑用户`, {
      action,
      userIds,
      reason,
      results
    })
    
    res.json({
      success: true,
      code: 200,
      data: { results },
      message: '批量处理完成'
    })
  } catch (error) {
    logger.error('批量处理可疑用户失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '批量处理可疑用户失败'
    })
  }
})

module.exports = router